// components/upload/index.js
import {$http, $util} from '@bana/miniapp-common-util'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    maxNum: { // 属性名
      type: Number,
      value: 9
    },
    type: {// 上传类型，默认image
      type: String,
      value: 'image'
    },
    rootPath: {// 根路径 默认空
      type: String,
      value: ''
    },
    sizeW: {
      type: String,
      value: '222rpx'
    },
    margin: {
      type: String,
      value: '18rpx'
    },
    del_margin_l: {
      type: String,
      value: '180rpx'
    },
    list: {
      type: Array,
      value: []
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    uploaderList: [],
    uploaderNum: 0,
    showUpload: true,
    uploadParam: {},
    showVideo: false,
    videoSrc: '',
    typeList: [
      {
        id: 'image',
        name: '上传图片'
      },
      {
        id: 'video',
        name: '上传视频'
      }
    ]
  },
  attached() {
    const that = this
    this.initOssSignFormLocal((resultData) => {
      that.setData({
        uploadParam: resultData
      })
    })
    this.setData({
      uploaderList: this.properties.list,
      showUpload: this.properties.list.length < this.properties.maxNum
    })
  },
  created() {
    // const that = this
    // this.initOssSignFormLocal((resultData) => {
    //   that.setData({
    //     uploadParam: resultData
    //   })
    // })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    initOssSignFormLocal(callback) {
      const that = this
      const expireTime = 2 // 离失效还有几分钟就不能使用的sign
      try {
        const localData = wx.getStorageSync('ossSign')
        if (localData) {
          if (localData.expire - new Date().getTime() / 1000 > expireTime * 60) {
            callback(localData)
            console.log('从本地读取图片')
            return
          }
        }
        that.initOssSignFromRemote(callback)
      } catch (e) {
        that.initOssSignFromRemote(callback)
      }
    },
    initOssSignFromRemote(callback) {
      const that = this
      const rootPath = that.data.rootPath || ''
      $http.post({
        url: rootPath + 'attach/ossSign',
        success(res) {
          console.log('从后台读取ossSign', res)
          wx.setStorageSync('ossSign', res.data.resultData)
          callback(res.data.resultData)
        }
      })
    },
    // 删除图片
    clearImg(e) {
      const targetIndex = e.currentTarget.dataset.index
      const newList = this.data.uploaderList.filter((item, index) => index !== targetIndex)
      const deleteFile = this.data.uploaderList[targetIndex]
      this.setData({
        uploaderNum: this.data.uploaderNum - 1,
        uploaderList: newList,
        showUpload: true
      })
      this.executeChange(deleteFile)
    },
    // 展示图片
    showImg(e) {
      const that = this
      wx.previewImage({
        urls: that.data.uploaderList.map(item => item.path),
        current: that.data.uploaderList[e.currentTarget.dataset.index].path
      })
    },
    // 展示视频
    showVideo(e) {
      console.log(e)
      const that = this
      that.setData({
        videoSrc: e.currentTarget.dataset.videopath,
        showVideo: true
      })
      console.log('showVideo', that.data.videoSrc)
      const videoContext = wx.createVideoContext('playVideo')
      videoContext.requestFullScreen()
      videoContext.play()
    },
    // 上传图片
    upload(e) {
      console.log(e)
      const that = this
      if (this.properties.type === 'image') {
        console.log('图片上传')
        // 图片上传
        wx.chooseImage({
          count: this.properties.maxNum - that.data.uploaderNum, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success(res) {
            console.log(res)
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            let tempFiles = res.tempFiles
            tempFiles = tempFiles.map(item => {
              item.type = that.properties.type
              return item
            })
            console.log('附件', tempFiles)
            const uploaderList = that.data.uploaderList.concat(tempFiles)

            console.log('判断数量', uploaderList.length, that.properties.maxNum)
            if (uploaderList.length === that.properties.maxNum) {
              that.setData({
                showUpload: false
              })
            }
            that.setData({
              uploaderList,
              uploaderNum: uploaderList.length,
            })
            that.upload2Oss(res)
          }
        })
      } else if (this.properties.type === 'video') {
        console.log('视频上传')
        wx.chooseVideo({
          sourceType: ['album', 'camera'],
          success(res) {
            console.log('视频已上传', res)
            const tempFiles = [{
              path: res.tempFilePath,
              size: res.size,
              thumbTempFilePath: res.thumbTempFilePath,
              type: that.properties.type
            }]
            that.upload2Oss({tempFiles})
          }
        })
      }
    },
    saveAliyun(data, callback) {
      const that = this
      const rootPath = that.data.rootPath || ''
      $http.post({
        url: rootPath + 'attach/save/aliyun',
        data,
        success({data}) {
          callback(data.resultData)
        }
      })
    },
    upload2Oss(res) {
      const that = this
      // const tempFilePaths = res.tempFilePaths
      const tempFiles = res.tempFiles
      if (tempFiles.length > 0) {
        tempFiles.forEach(file => {
          console.log('upload2Oss', file)
          wx.uploadFile({
            url: this.data.uploadParam.domain.replace('http:', 'https:'),
            filePath: file.path,
            name: 'file',
            formData: {
              name: file.path,
              // eslint-disable-next-line no-template-curly-in-string
              key: this.data.uploadParam.dir + '/${filename}',
              policy: this.data.uploadParam.policy,
              OSSAccessKeyId: this.data.uploadParam.accessid,
              success_action_status: '200',
              signature: this.data.uploadParam.signature,
            },
            success(res2) {
              console.log('chooseImage success, temp path is: ', file, res2)

              const fileName = that.getWxFileName(file.path)

              const saveUrl = that.data.uploadParam.dir + '/' + fileName

              that.saveAliyun({
                url: saveUrl,
                name: fileName,
                size: file.size,
                type: $util.getFileType(file.path)
              },
              (code) => {
                file.code = code
                file.path = that.data.uploadParam.domain + '/' + saveUrl
                console.log('保存附件成功', code, that.data.uploadParam, that.data.uploaderList)
                if (that.properties.type === 'video') {
                  const uploaderList = that.data.uploaderList.concat([{
                    code,
                    path: `${that.data.uploadParam.domain}/${that.data.uploadParam.dir}/${fileName}`,
                    size: res.size,
                    thumbTempFilePath: res.thumbTempFilePath,
                    type: that.properties.type
                  }])

                  if (uploaderList.length === 1) {
                    that.setData({
                      showUpload: false
                    })
                  }
                  that.setData({
                    uploaderList,
                    uploaderNum: uploaderList.length,
                  })
                }

                that.executeChange(file)
              })
            },
            fail({errMsg}) {
              console.log('upladImage fail, errMsg is: ', errMsg)
              wx.showToast({
                title: '上传失败',
                icon: 'none',
                duration: 1000
              })
            }
          })
        })
      }
    },
    getRandomFile() {
      const date = new Date()
      const monthStr = date.format('yyyy-MM')
      // let milliseconds = date.getMilliseconds();
      return '/' + monthStr + '/' + $util.random_string(10)
    },
    getWxFileName(tt) {
      return tt.substring(tt.lastIndexOf('/') + 1)
    },
    executeChange(file) {
      console.log('file finish change', file)
      // 通过判断uploaderList 中所有的file都已经有了code字段，来出发外部的change事件
      if (!this.data.uploaderList.some(item => item.code === undefined)) {
        // wx.showToast({
        //   title: '上传成功',
        //   icon: 'success',
        //   duration: 1000
        // })
        // 触发一个uploadChange事件，上传列表的内容发生变化
        console.log('triggerUploadChange', this.data.uploaderList)
        this.triggerEvent('uploadchange', JSON.parse(JSON.stringify(this.data.uploaderList)), {})
      }
    },
    typeListChange(e) {
      console.log('typeList change', e)
      const key = e.detail.value
      const selType = this.data.typeList[key]
      this.setData({
        type: selType.id
      })
      console.log('现在的type', this.properties.type)
      this.upload(e)
    },
    onLoad() {
    }
  }
})
